#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <stdlib.h>
#include <stdio.h>

//prototypes
void init(void);

volatile int globalvar = 0;
int main(void)
{
	_delay_ms(5000);
	init();
	int i;
	int humidity=0;
	int temperature=0;
	while(1){
		_delay_ms(2000);
		DDRB = 0x01;
		PORTB = 0x00;
		//set PORTB pin0 up for output low
		_delay_ms(5);
//		PORTB  = 0x01;
//		for(i=0; i<45; i++);
		DDRB = 0x00;
		PORTB = 0x01;
		//set POSRTB pin0 to input with internal pull up

	
		while((PINB & _BV(PINB0))); //waits for sensor to pull low
	
		while(!(UCSR0A & _BV(UDRE0)));
		UDR0 = '1';
	
		while(!(PINB & _BV(PINB0))); //waits for sensor to pull high
	
		while(!(UCSR0A & _BV(UDRE0)));
		UDR0 = '2';		

		while((PINB & _BV(PINB0))); //waits for sensor to pull low indicating that it's ready 
						// to transmit

	
	
	
		for(i=0; i < 40; i++)
		{
			if(i == 16)
			{
				humidity = globalvar;
				globalvar = 0;
			}
			if(i == 32)
			{
				temperature = globalvar;
				globalvar = 0;
			}

	

			while(!(PINB & _BV(PINB0)));
			
			
			
			
			PCMSK1 = 0x01;
			TCCR0A = 0x01;
			while((PINB & _BV(PINB0)));		




		}

		while(!(UCSR0A & _BV(UDRE0)));
		UDR0 = '6';

/*
		char buf[10];
		//itoa(temperature, buf, 10);
		sprintf(buf, "%x", temperature);
		for(i = 0; i < 10; i++)
		{
		while(!(UCSR0A & _BV(UDRE0)));
		UDR0 = buf[i];
		}


		int temp_bits = temperature;
		for(i=0; i<16; i++)
		{
			while(!(UCSR0A & _BV(UDRE0)));
			if(temp_bits & 1)
				UDR0 = 0x31;
			else
				UDR0 = 0x30;
			
			temp_bits = temp_bits << 1;
		}
*/		
		while(!(UCSR0A & _BV(UDRE0)));
		if(temperature == 0)			
			UDR0 = 'Y';
		else 
			UDR0 = 'N';

		while(!(UCSR0A & _BV(UDRE0)));
		if(humidity == 0)			
			UDR0 = 'Y';
		else 
			UDR0 = 'N';


	}

	return 1;
}




void init(void)
{


	DDRB = 0x01;
	PORTB = 0x01;
	UCSR0A = 0x02;         //U2x=1
	UCSR0B |= 0x12;      //TX and RX are enabled for now
    UCSR0C =  0x06;       //no parity, stop 1 bit, 8data bits

	

	UBRR0H = 0x00;
	UBRR0L = 0x0c;//sets baud rate to 19200 on 2mHz frequency
	sei(); //activate global interrupts
	EIMSK = 0xc0;
	//set the pin change interrupt for PORTB PIN1
	

}


ISR(PCINT1_vect)
{
	if(TCNT0 > 0)
		globalvar |= 0x01;

	TCCR0A = 0x00;
	PCMSK0 = 0x00;
	globalvar = (globalvar << 1);


	TCNT0 = 0x00;

	



}
